import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css'// progress bar style
import { getToken } from '@/utils/auth' // getToken from cookie

NProgress.configure({ showSpinner: false })// NProgress Configuration

const witeList = ['/login', '/authredirect']

router.beforeEach((to, from, next) => {
  NProgress.start() // start progress bar
  if (getToken()) { // determine if there has token
    /* has token*/

    if (!store.getters.i18Meaning.isloadI18) {
      const i18Meaning = JSON.parse(localStorage.getItem('i18nKey')) || {}
      i18Meaning.isloadI18 = 'yes'
      store.dispatch('addI18', i18Meaning)
    }

    if (to.path === '/login' || to.path === '/') {
      next({ path: '/home' })
      NProgress.done()
    } else {
      if (store.getters.menus.length === 0) { // 判断当前用户是否已经获取菜单信息
        store.dispatch('getMenus').then(res => { // 获取菜单
          const menus = res // note:menus is array
          store.dispatch('GenerateRoutes', { menus }).then(response => { // 根据菜单生成路由表
            store.dispatch('setCommonOperations', response)
            router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
            if (!store.getters.orgTree) { // 获取单位树
              store.dispatch('setOrgTree')
            }
            next({ ...to, replace: true }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
          })
        }).catch((err) => {
          store.dispatch('FedLogOut').then(() => {
            Message.error(err || 'Verification failed, please login again')
            next({ path: '/login' })
          })
        })
      } else {
        next()
      }
    }
  } else {
    if (witeList.indexOf(to.path) >= 0) {
      next()
    } else {
      next('/login') // 否则全部重定向到登录页
    }
    NProgress.done() // if current page is login will not trigger afterEach hook, so manually handle it
  }
})

router.afterEach(() => {
  NProgress.done() // finish progress bar
})
